package com.naldo.goodcard;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
 
import android.app.Activity;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.naldo.goodcard.SQL.Cartao;
import com.naldo.goodcard.SQL.DbAdapter;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ConsultActivity extends Activity implements OnClickListener {

	DbAdapter datasource;
	Cartao cartao;

	private TextView value;
	private ProgressBar pb;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_consult);
		
		value=(TextView)findViewById(R.id.textView1);
		pb=(ProgressBar)findViewById(R.id.progressBar1);
		pb.setVisibility(View.GONE);
		
		// return;

//		// http://www.lucazanini.eu/2012/android/the-android-os-networkonmainthreadexception-exception/?lang=en
		this.datasource = new DbAdapter(this);

		Intent item = getIntent();

		long _id = item.getLongExtra("_id", 0);
		cartao = datasource.getCartao(_id);
		String result = "";
		
		pb.setVisibility(View.VISIBLE);	
		new MyAsyncTask().execute("","",result);
		
		value.setText("Saldo: R$ " + result);	
		
//		HttpClient client = new DefaultHttpClient();
//		HttpPost post = new HttpPost(
//				"https://www.goodcard.com.br/beneficio/Login/home.cfm");
//
//		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
//		pairs.add(new BasicNameValuePair("nr_cartao", cartao.getNumero()));
//		pairs.add(new BasicNameValuePair("cpf", cartao.getCPF()));

		// post.setEntity(new UrlEncodedFormEntity(pairs));
		// HttpResponse response = client.execute(post);
	}
	
	public void onClick(View v) {
		// TODO Auto-generated method stub
			if(value.getText().toString().length()<1) {
				// out of range
				Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
			}
			else
			{
				pb.setVisibility(View.VISIBLE);						
			}
	} 
 	
	private class MyAsyncTask extends AsyncTask<String, String, String>{
		@Override
		
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub			
			return postData(params[0]);
		}
 
		protected void onPostExecute(String result){
			pb.setVisibility(View.GONE);
			value.setText("Saldo: R$ " + result);			
//			Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
		}

		protected void onProgressUpdate(Integer... progress){
			pb.setProgress(progress[0]);
		}
 
		public String postData(String valueIWantToSend) {
			// Create a new HttpClient and Post Header
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("https://www.goodcard.com.br/beneficio/Login/ChkLogin.cfm");

//https://www.goodcard.com.br/beneficio/Login/ChkLogin.cfm?nr_cartao=6394010107640765&cpf=29932123897
//			HttpPost httppost = new HttpPost("http://www.goodcard.com.br/beneficio/Login/ChkLogin.cfm?nr_cartao=&" + cartao.getNumero() + "cpf=" + cartao.getCPF() + "&s=");
			//https://www.goodcard.com.br/beneficio/Login/home.cfm
//			https://www.goodcard.com.br/beneficio/Login/ChkLogin.cfm?nr_cartao=6394010107640765&cpf=29932123897&s=			
//https://www.goodcard.com.br/beneficio/Login/ChkLogin.cfm?nr_cartao=6394010107640765&cpf=29932123897	
			
			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("nr_cartao", cartao.getNumero()));
				nameValuePairs.add(new BasicNameValuePair("cpf", cartao.getCPF()));
				
				String result = "";
				BufferedReader inBuffer;
				
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//				
				httppost.addHeader("Host", "www.goodcard.com.br");
				httppost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httppost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0"); 
				
//				httppost.addHeader("Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3");
//				httppost.addHeader("Accept-Encoding", "gzip, deflate");
//				httppost.addHeader("Cookie", "CFID=6872273; CFTOKEN=d35ccbc14a29ee68-B9D8BBA4-0123-8C3F-C50627FF43025855; __utma=125299100.1109826557.1390596285.1390596285.1390596285.1; __utmz=125299100.1390596285.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); JSESSIONID=4e303a93c2a52a7b2fbbd3a71d265f37103d; GOODMED_CFAJAX_ESTADO=0; GOODMED_CFAJAX_CIDADE=0");
//				httppost.addHeader("Connection", "keep-alive");
				

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);
				
				inBuffer = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent()));

					StringBuffer stringBuffer = new StringBuffer("");
					String line = "";
					String newLine = System.getProperty("line.separator");
					while ((line = inBuffer.readLine()) != null) {
						stringBuffer.append(line + newLine);
					}
					inBuffer.close();

					result = stringBuffer.toString();
					String resultX = "";
					
					int startPosition = result.indexOf("Seu saldo&nbsp;hoje &eacute; de&nbsp;<b>R$&nbsp;") + "Seu saldo&nbsp;hoje &eacute; de&nbsp;<b>R$&nbsp;".length();  
					int endPosition = result.indexOf("</b></span><br />", startPosition);  
					resultX = result.substring(startPosition, endPosition); 
					
//					onPostExecute(resultX);
					return resultX;
					
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
//			onPostExecute("");
			
			return "";
		}
 
	}
	
	
}